#!/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = 'scotty@google.com (Scotty Allen)'

import logging 
from google.appengine.ext import db

class ToDoneUser(db.Model):
  user = db.UserProperty(required=True)

  def Count():
    users = db.GqlQuery("SELECT * FROM ToDoneUser")
    return users.count()
  Count = staticmethod(Count)

  def GetOrCreateUser(user):
    todone_user = db.GqlQuery("SELECT * from ToDoneUser WHERE user = :1", user).get()
    if not todone_user:
      todone_user = ToDoneUser(user = user)
      todone_user.put()
    return todone_user
  GetOrCreateUser = staticmethod(GetOrCreateUser)

class TaskList(db.Model):
  name = db.StringProperty()
  owner = db.UserProperty(required=True)
  color = db.StringProperty()
  is_shown = db.BooleanProperty(required=True, default=True)
  is_completed_tasks_shown = db.BooleanProperty(required=True, default=True)
  date_created = db.DateTimeProperty(auto_now_add=True)
  todone_user = db.Reference(ToDoneUser, default=None, required=False)

  def GetTaskListsForOwner(owner):
    return db.GqlQuery("SELECT * FROM TaskList WHERE owner = :1 ORDER BY "
                       "date_created", owner)
  GetTaskListsForOwner = staticmethod(GetTaskListsForOwner)

  def Tasks(self):
    tasks = []
    for task in db.GqlQuery("SELECT * FROM Task WHERE task_list = :1 ORDER BY "
                            "date_created", self):
      tasks.append(task)
    return tasks

  def GetTaskLists(limit, offset):
    return db.GqlQuery("SELECT * from TaskList").fetch(limit, offset)
  GetTaskLists = staticmethod(GetTaskLists)

  def AddToDoneUsers(limit, offset):
    """Adds a todone user to a number of tasklists that don't have one.

    Args:
      limit: the maximum number of users to convert.

    Returns:
      A list of the TaskLists modified.
    """
    task_lists = TaskList.GetTaskLists(limit, offset)
    for task_list in task_lists:
      user = ToDoneUser.GetOrCreateUser(task_list.owner)
      task_list.todone_user = user
      task_list.put()

    return task_lists
  AddToDoneUsers = staticmethod(AddToDoneUsers)

class Task(db.Model):
  title = db.StringProperty(required=True)
  done = db.BooleanProperty(required=True)
  date_done = db.DateTimeProperty()
  date_created = db.DateTimeProperty(auto_now_add=True)
  task_list = db.Reference(TaskList)

class Counter(db.Model):
  name = db.StringProperty(required=True)
  value = db.IntegerProperty(required=True, default=0)

  def DoIncrement(key, amount):
    counter = db.get(key)
    counter.value += amount
    counter.put()
  DoIncrement = staticmethod(DoIncrement)

  def Increment(self, amount=1):
    return db.run_in_transaction(Counter.DoIncrement, self.key(), amount)

  def GetCounter(name):
    counter = db.GqlQuery("SELECT * FROM Counter WHERE name = :1", name).get()
    if not counter:
      counter = Counter(name=name)
      counter.put()
    return counter
  GetCounter = staticmethod(GetCounter)

  def DoClear(key):
    counter = db.get(key)
    counter.value = 0
    counter.put()
  DoClear = staticmethod(DoClear)

  def Clear(self):
    db.run_in_transaction(Counter.DoClear, self.key())
